<?php

/*
    picopress - A lightweighed online publishing system
    Copyright (C) 2010  Martin Burkert <martin@burkert.de>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
    
*/

class PicoVariableInputParser extends CoreParser implements Parser {

    public function parse ($content) {
    
        
        $template = $this->get_template();
        $content_parsed = '';
        $lines_parsed = 0;
        $lines = preg_split("/(\r?\n)/", $content);
        
        foreach($lines as $line){

            if(preg_match('/^\s*\$([A-Za-z0-9_]{1,32})\s*=\s(.*)\s*$/', $line, $matches)) {

                $template->assign_var($matches[1], $matches[2]);
                $lines_parsed++;
                
            }else if(preg_match('/^\s*@([A-Za-z0-9_]{1,32})\s*=\s(.*)\s*$/', $line, $matches)) {

                $arr_elements = array();
                $buffer = '';
                $l = strlen($matches[2]);
                
                for($i=0; $i<$l; $i++){
                    $c = substr($matches[2],$i,1);
                    if($c == "\\" && $i+1<$l && substr($matches[2],$i+1,1) == ','){
                        $buffer .= ',';
                        $i++; 
                    } else if ($c == "," || $i == $l-1) {
                        if($i == $l-1) $buffer .= $c;
                        $element = trim($buffer);
                        if (strlen($element) > 0) array_push($arr_elements, trim($buffer));
                        $buffer = '';
                    } else {
                        $buffer .= $c;
                    }    
                }
                
                $template->assign_var($matches[1], $arr_elements);            
                $lines_parsed++;
            } else {
                break;
            }

        }

        return implode("\n", array_slice($lines, $lines_parsed));
    
    }

}


?>